from common.unit import AndroidUI
from common.home_page import HomePageObject
from common.qr_code import QRCodeX
from object.lnitial.lnitial_page import LnitialObject
from object.recover.recover_bags_mode import RecoverBagObject
import time
import linecache
import os


# 回收界面的重启蓝牙，置零，输入重量，科室和护士认证，选择不同类型的垃圾进行打印，对可回收和自定义垃圾打印，删除垃圾断言麻烦，暂不做
class RecoverTest:
    def __init__(self):
        self.unit = AndroidUI
        self.home = HomePageObject()
        self.qrcode = QRCodeX()
        self.ln = LnitialObject()
        self.re = RecoverBagObject()
        self.driver = AndroidUI.get_webdriver()

    def back_button(self):
        self.driver.press('back')


    # 清理人登录
    # def check_login(self):
    #     # self.unit.scan(self.qrcode.zhaoqingli)
    #     try:
    #         self.unit().isElement("id","com.bluephone:id/systemSet4")
    #         self.unit.scan(self.qrcode.zhaoqingli)
    #         print("登录成功")
    #     except:
    #         print("已经登录")

    # 清理人登录
    def check_login(self):
        # self.unit.scan(self.qrcode.zhaoqingli)
        if AndroidUI().assert_in_text("收集中", self.home.home_page()):
            print("已经登录")
        else:
            self.unit.scan(self.qrcode.zhaoqingli)
            print("登录成功")

    # 扫码进入回收界面，并且返回首页
    def enter_recover_scan(self):
        self.unit.scan(self.qrcode.waike)
        if self.unit.assert_in_text("认证科室",self.re.department_button()):
            print("扫码认证科室失败")
            AndroidUI.capture()
            AndroidUI().write_result("扫码认证科室", "失败")
        else:
            print("扫码认证科室成功")
            AndroidUI().write_result("扫码认证科室", "成功")

    # 点击回收按钮，进入回收界面，这个没有用了
    def enter_recover_click(self):
        try:
            self.home.recover_button().click()
            self.re.restart_bluetooth_button()
            print("点击回收按钮进入回收界面成功")
            AndroidUI().write_result("点击回收按钮进进入回收界面", "成功")
        except:
            print("点击回收按钮进进入回收界面失败")
            AndroidUI.capture()
            AndroidUI().write_result("点击回收按钮进进入回收界面", "失败")
            # self.driver.quit()

    # 重启蓝牙，没有这个
    # def restart_bluetooth(self):
    #     self.re.restart_bluetooth_button().click()
    #     print("点击重启蓝牙")
    #     AndroidUI().write_result("点击重启蓝牙", "成功")

    # 置零
    def clear_zero(self, weight):
        if weight == "不置零":
            print('不进行置零操作')
        else:
            self.re.clear_zero_button().click()  # 如果有连接秤就置零，后期优化为可选
            weight_text = self.re.weight_button().get_text()
            # print(weight_text)
            if weight_text == "点击手输重量上传":
                # if "上传" in weight_text:
                AndroidUI().write_result("点击置零", "未连接蓝牙")
                print("点击置零按钮，提示未连接蓝牙")
                self.re.weight_button().click()
                self.re.weight_input().send_keys(weight)
                self.re.ok_button().click()
                print(f'设置重量为{weight}kg')
            elif "0.00" in self.re.weight_button().text:
                AndroidUI().write_result("点击置零", "置零成功")
                print("点击置零按钮，置零成功")
            else:
                AndroidUI().write_result("点击置零", "失败")
                AndroidUI.capture()
                print("点击置零按钮，置零失败")

    # 科室认证扫码，内科
    def department_scan(self):
        self.unit.scan(self.qrcode.zidonghuakeshi)  # 扫内科的二维码
        if "自动化" in self.re.department_button().get_text():
            print('扫码认证自动化科室成功')
            AndroidUI().write_result("扫码认证自动化", "成功")
        else:
            print('扫码认证自动化科室失败')
            AndroidUI().write_result("扫码认证自动化", "失败")
            AndroidUI.capture()

    # 手动选择科室
    def department_click(self, name):
        self.re.department_button().click()
        # self.driver.find_element_by_android_uiautomator('new UiSelector().textContains("外科")').click()
        # self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{name}")').click()
        try:
            self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{name}")').click()
            # print("选择成功。开始断言")
            if name in self.re.department_button().text:
                print(f'点击科室，选择认证{name}科室成功')
                AndroidUI().write_result(f"扫码认证{name}", "成功")
            else:
                print(f'选择认证{name}科室失败')
                AndroidUI().write_result(f"选择认证{name}", "失败")
                AndroidUI.capture()
        except:
            print(f'选择认证{name}科室失败')
            AndroidUI().write_result(f"选择认证{name}", "失败")
            AndroidUI.capture()

    # 扫码认证护士
    def nurse_scan(self):
        self.unit.scan(self.qrcode.zidonghuahushi)  # 扫钱护士的二维码
        if "护士" in self.re.nurse_button().get_text():
            print('扫码认证护士成功')
            AndroidUI().write_result("扫码认证护士", "成功")
        else:
            print('扫码认证护士失败')
            AndroidUI().write_result("扫码认证护士", "失败")
            AndroidUI.capture()

    # 读取并删除读取的行,返回读取的那个数值,count为删除的行数，count2为读取第几列（返回的全部是是首次打开的文件低X行）
    def read_delete_first_lines(self,filename, count,count2):
        n = linecache.getline(filename,count2).strip()  # 返回文件第count行数据
        with open(filename, 'r') as old_file:
            old = old_file.readlines()
        with open(filename, 'w') as new_file:
            # print(old[count:])
            # print("...............................................................")
            # [1:]去掉列表中第一个元素（下标为0），去后面的元素进行操作
            # str.join(item),str表示字符串（字符），item表示一个成员，注意括号里必须只能有一个成员
            #todo ','.join('abc')的介绍

            # 例如','.join('abc')的含义是“将字符串abc中的每个成员以字符','分隔开再拼接成一个字符串”，输出结果为：'a,b,c'
            new = ''.join(old[count:])
            # print(new)
            new_file.write(new)
        return n

    #扫描垃圾袋标签码,type是类型,res是读取第几行
    def scan_rubbish(self,filename,type,res,weight,conn):
        # filename=os.path.dirname(os.path.dirname(__file__))+'/date/感染性.csv'
        scan_info=self.read_delete_first_lines(filename,1,res)
        # print(f"{scan_info}scan_info是.........................")
        AndroidUI().scan(scan_info)
        toast_message2 = self.driver.toast.get_message(default="没有toast弹窗")
        # AndroidUI().scan(self.read_delete_first_lines(r'../../date/感染性.csv',1))
        if AndroidUI().assert_in_text('请选择垃圾类别',self.re.choice_text()):
            print(f"扫描类型{type}标签码成功")
            AndroidUI().write_result(f"扫描医废类型{type}标签码", "成功")
            if conn=='ok':
                self.notinput_weight_recover(weight)
            else:
                self.input_weight_recover(weight)
            time.sleep(1)
        else:
            print(f"扫描类型{type}标签码失败，toast弹窗为：{toast_message2}")
            AndroidUI().write_result(f"扫描类型{type}标签码,toast提示为：{toast_message2}", "失败")
            AndroidUI.capture()
            time.sleep(1)

    #手动输入重量,并且收集，未连接蓝牙秤的时候
    def input_weight_recover(self,weight):
        try:
            self.re.recover_info().click()
            if AndroidUI().assert_in_text('请手动输入重量',self.re.confirm_weight()):
                print('弹出输入重量弹窗成功')
                try:
                    self.re.input_box().send_keys(weight)   #输入重量
                    self.re.weight_ok_button().click()      #确定按钮
                    time.sleep(0.5)
                    #通过弹窗是否有weight对应的数字断言
                    if AndroidUI().assert_in_text(f'{weight}kg',self.re.recover_info()):
                        print("手动输入重量成功")
                        AndroidUI().write_result(f"手动输入重量，重量展示", "成功")
                        try:
                            self.re.recover_button().click()    #点击垃圾，进行回收垃圾
                            toast_message1=self.driver.toast.get_message()
                            if toast_message1=="回收成功":
                                print(f'返回的toast为：{toast_message1}，回收成功')
                            else:
                                print(f'回收失败,返回的toast为：{toast_message1}')
                        except:
                            print("shoujishibai")

                    else:
                        print('手动输入失败')
                        AndroidUI().write_result("手动输入重量，重量展示", "失败")
                        AndroidUI.capture()
                except:
                    print("没有找到重量输入框元素或确定按钮")
                    AndroidUI().write_result("没有找到重量输入框元素或确定按钮", "失败")
                    AndroidUI.capture()
            else:
                print('输入重量失败')
                AndroidUI().write_result("重量弹窗弹出", "失败")
                AndroidUI.capture()
        except:
            print("输入重量的弹窗未弹出")
            AndroidUI().write_result("重量弹窗弹出", "失败")
            AndroidUI.capture()

        # 手动输入重量,并且收集，未连接蓝牙秤的时候

    def notinput_weight_recover(self, weight):
        try:
            self.re.recover_info().click()
            if AndroidUI().assert_in_text('请手动输入重量', self.re.confirm_weight()):
                print('弹出输入重量弹窗成功')
                try:
                    self.re.input_box().send_keys(weight)  # 输入重量
                    self.re.weight_ok_button().click()  # 确定按钮
                    # 通过弹窗是否有weight对应的数字断言
                    try:
                        self.re.recover_button().click()  # 点击垃圾，进行回收垃圾
                        toast_message1 = self.driver.toast.get_message()
                        if toast_message1 == "回收成功":
                            print(f'返回的toast为：{toast_message1}，回收成功')
                        else:
                            print(f'回收失败,返回的toast为：{toast_message1}')
                    except:
                        print("shoujishibai")
                except:
                    print("没有找到重量输入框元素或确定按钮")
                    AndroidUI().write_result("没有找到重量输入框元素或确定按钮", "失败")
                    AndroidUI.capture()
            else:
                print('输入重量失败')
                AndroidUI().write_result("重量弹窗弹出", "失败")
                AndroidUI.capture()
        except:
            print("输入重量的弹窗未弹出")
            AndroidUI().write_result("重量弹窗弹出", "失败")
            AndroidUI.capture()

    #todo 路径写法；对所有医废类型都回收两次,scan_rubbish的最后位参数，相同类型得比上次多1，前面读删文件函数有问题，
    def recover_all_type(self,connect):
        curPath = os.path.abspath(os.path.dirname(__file__))  # 获取上级目录位置D:\rj自动化\GUI_UI2\case\recover
        rootPath = curPath[:curPath.find("myProject\\") + len("myProject\\")]  # 获取myProject，也就是项目的根路径D:\rj自动化\
        # dataPath = os.path.abspath(rootPath + 'data/train.csv') # 获取tran.csv文件的路径



        self.scan_rubbish(rootPath+'GUI_UI2/date/感染性.csv','感染性1',res=1,weight=1,conn=connect)
        self.re.del_button(1).click()   #点击删除
        self.re.del_ok_button().click()     #确定按钮
        print("删除医废成功")

        # #批量删除医废袋
        # for i in range(1,5):
        #     self.re.del_button(1).click()
        #     self.re.del_ok_button().click()


        self.scan_rubbish(rootPath+'GUI_UI2/date/损伤性.csv','损伤性2',res=2,weight=1.5,conn=connect)
        self.re.del_button(1).click()   #点击删除
        self.re.del_ok_button().click()     #确定按钮
        # self.scan_rubbish(rootPath+'GUI_UI2/date/化学性.csv','感染性3',res=3,weight=2,conn=connect)
        # self.scan_rubbish(rootPath+'GUI_UI2/date/病理性.csv','感染性4',res=4,weight=2.5,conn=connect)
        # self.scan_rubbish(rootPath+'GUI_UI2/date/感染性.csv','感染性5',res=5,weight=3,conn=connect)
        # self.input_weight_recover(1.2)


    # 选择医废类型
    def choose_type(self, name):
        # is_selected()返回的结果是True和False，is_displayed()：判断元素是否显示，is_selected()：判断元素是否选中状态
        # if self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{name}")').is_selected():
        #     print("选中")
        # else:
        #     print('没有选中')

        try:
            self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{name}")').click()
            if self.driver.find_element_by_android_uiautomator(
                    f'new UiSelector().textContains("{name}")').is_selected():
                print(f"选择医废类型{name}成功")
                AndroidUI().write_result(f"选择医废类型{name}", "成功")
            else:
                print(f"选择医废类型{name}失败")
                AndroidUI().write_result(f"选择类型{name}", "失败")
                AndroidUI.capture()
        except:
            print(f'选择医废类型{name}失败')
            AndroidUI().write_result(f"选择医废类型{name}", "失败")
            AndroidUI.capture()

    # 打印指定垃圾袋
    def print_type_bags(self):
        # self.choose_type(m)     #选择垃圾类型
        # time.sleep(3)
        # self.print_bags()       #点击打印按钮
        # new = f"，{m}"
        # try:
        #     self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{new}")')
        #     print(f"打印{m}垃圾成功")
        #     AndroidUI().write_result(f"打印医废类型为{m}的垃圾", "成功")
        # except:
        #     print(f"打印{m}垃圾失败")
        #     AndroidUI().write_result(f"打印医废类型为{m}的垃圾", "失败")
        #     AndroidUI.capture()

        weight_text = str(self.re.weight_button().text).strip('KG')
        # print(weight_text)
        with open(r"D:\rj自动化\GUI_Appium\date\感染性.csv", encoding='utf-8') as file:
            content = file.readlines()

            for i in content:
                self.choose_type(i.strip())
                # m=i.strip()
                time.sleep(3)
                self.print_bags()

                m = i.strip()
                new = f"，{m}"
                # new=f"{m}{weight_text}"
                # print(new)
                try:
                    self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{new}")')
                    print(f"打印{m}垃圾成功")
                    AndroidUI().write_result(f"打印医废类型为{m}的垃圾", "成功")
                except:
                    print(f"打印{m}垃圾失败")
                    AndroidUI().write_result(f"打印医废类型为{m}的垃圾", "失败")
                    AndroidUI.capture()





    # 选择所有医废，并打印
    def choose_all_type(self):
        weight_text = str(self.re.weight_button().text).strip('KG')
        # print(weight_text)
        with open(r"D:\rj自动化\GUI_Appium\date\type.csv", encoding='utf-8') as file:
            content = file.readlines()

            for i in content:
                self.choose_type(i.strip())
                # m=i.strip()
                time.sleep(3)
                self.print_bags()

                m = i.strip()
                new = f"，{m}"
                # new=f"{m}{weight_text}"
                # print(new)
                try:
                    self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{new}")')
                    print(f"打印{m}垃圾成功")
                    AndroidUI().write_result(f"打印医废类型为{m}的垃圾", "成功")
                except:
                    print(f"打印{m}垃圾失败")
                    AndroidUI().write_result(f"打印医废类型为{m}的垃圾", "失败")
                    AndroidUI.capture()

                # #垃圾袋列表第一条数据
                #                 # first_list=self.driver.find_element_by_xpath("//android.widget.TextView[@resource-id='com.bluephone:id"
                #                 #                                              "/item_text' and @text='NO.2，损伤性5kg2020-10-08 08:39:25']")
                #                 # print(first_list)

    # NO.1，感染性6kg 2020-10-07 15:51:28
    '''
    从上往下
    //android.widget.ListView[@resource-id='com.bluephone:id/list_data']/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.ImageView[1]
    //android.widget.ListView[@resource-id='com.bluephone:id/list_data']/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.ImageView[1]
    //android.widget.FrameLayout[@resource-id='android:id/content']/android.widget.LinearLayout[1]
    
    
    //android.widget.ListView[@resource-id='com.bluephone:id/list_data']/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.ImageView[1]
    //android.widget.ListView[@resource-id='com.bluephone:id/list_data']/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.ImageView[1]
    //android.widget.ListView[@resource-id='com.bluephone:id/list_data']/android.widget.LinearLayout[3]/android.widget.LinearLayout[1]/android.widget.ImageView[1]
    '''

    # 返回首页
    def back_home(self):
        try:
            self.re.back_button().click()
            self.home.home_page()
            print("返回首页成功")
            AndroidUI().write_result("返回首页", "成功")
        except:
            print("返回首页失败")
            self.back_button()
            AndroidUI.capture()
            AndroidUI().write_result("返回首页界面", "失败")

    # def write_result(self,operation,result):
    #     now_time = time.strftime('%Y%m%d_%H%M%S')
    #     # with open(r"D:\rj自动化\GUI_Appium\report\2"+self.result_name,"a+") as file:
    #     with open(r"../report/测试.csv","a") as file:
    #     # with open("../report/"+self.result_name,"a+") as file:
    #         line='%s,%s,%s\n'% (operation,result,now_time)
    #         file.write(line)

    def ceshi(self):
        self.unit().write_result("cesjo", "sdsads")

    def start_test(self,conn):
        self.check_login()
        self.enter_recover_scan()
        # self.enter_recover_click()  #纯扫描版没必要
        # self.clear_zero(weight)  # 如果未连接情况下，则输入0.5kg

        self.department_scan()
        # self.department_click(keshi)
        self.nurse_scan()
        # self.scan_rubbish('../../date/感染性.csv','感染性')       #扫描袋标签码
        # self.input_weight_recover('1.5')
        self.recover_all_type(conn)        #对所有的医废进行收集，各两袋,ok为连接秤，其他为未连接
        # self.choose_all_type()      #打印所有类型
        # self.recyclables()          #打印可回收三类型
        # self.div_type()             #打印自定义垃圾
        # self.print_type_bags()
        # self.back_home()
    def test(self):
        self.unit.scan(self.qrcode.zhaoqingli)


if __name__ == '__main__':
    re = RecoverTest()
    # # re.check_login()
    # # re.scan_rubbish()
    # re.start_test('ok')  #
    re.test()
    # re.start_test('ok')   #
    # for i in range(20):






    # curPath = os.path.abspath(os.path.dirname(__file__))    #获取上级目录位置D:\rj自动化\GUI_UI2\case\recover
    # rootPath = curPath[:curPath.find("myProject\\") + len("myProject\\")]  # 获取myProject，也就是项目的根路径D:\rj自动化\
    # print(curPath)
    # print(rootPath)
    # root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))                 #D:\rj自动化\GUI_UI2\case
    # print(root_path)

